<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      span {
        display: inline-block;
        width: 100px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        border: 1px solid #000;
        margin-right: 10px;
        cursor: pointer;
      }

      .box {
        width: 600px;
        height: 400px;
        position: relative;
      }

      .box div {
        width: 100%;
        height: 100%;
        display: none;
        position: absolute;
        top: 0;
      }

      .box div:nth-of-type(1) {
        background-color: bisque;
      }

      .box div:nth-of-type(2) {
        background-color: #6ec9ed;
      }

      .box div:nth-of-type(3) {
        background-color: #8e6ee6;
      }

      .active {
        background-color: yellow;
      }

      .show {
        display: block !important;
      }

      /* .s1.active .s1元素有class active
        span.active span元素class 有 active 
      */
      /* .s1.active ~ .box div:nth-of-type(1) {
        display: block;
      }

      .s2.active ~ .box div:nth-of-type(2) {
        display: block;
      } */
    </style>
  </head>
  <body>
    <!-- 自定义属性 -->
    <span class="span s1 active" data-index="0">tab1</span>
    <span class="span s2" data-index="1">tab2</span>
    <span class="span s3" data-index="2">tab3</span>
    <span class="span s3" data-index="3">tab4</span>
    <div class="box">
      <div class="show">tab1</div>
      <div>tab2</div>
      <div>tab3</div>
      <div>tab4</div>
    </div>

    <script type="text/javascript">
      // querySelector 选中一个元素, querySelectorAll 选中多个元素
      var spans = document.querySelectorAll(".span");
      var divs = document.querySelectorAll(".box div");

      // 循环每一个 span 元素
      for (var i = 0; i < spans.length; i++) {
        // 添加事件监听  元素.addEventListener("mouseover", (event) => {}); 元素.onmouseover = (event) => {};
        spans[i].onmouseover = function (event) {
          // 元素.dataset.index 获取元素自定义属性 data-index 的值
          var index = this.dataset.index;
          // 移除之前的 .active class  元素.classList 获取元素的 class
          document.querySelector(".active").classList.remove("active");
          document.querySelector(".show").classList.remove("show");
          // 给当前元素添加 .active class
          this.classList.add("active");
          divs[index].classList.add("show");
        };
      }
    </script>
  </body>
</html>
